package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.utils.CacheUtil;
import cn.tedu._03vehicle.mapper.NoticeMapper;
import cn.tedu._03vehicle.pojo.vo.NoticeListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "03.公告管理模块")
@RestController
@RequestMapping("/v1/notice")
public class NoticeController {
//    @Autowired
//    private RedisTemplate<String, Serializable> redisTemplate;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private NoticeMapper noticeMapper;
    //公告列表
    @GetMapping("list")
    @ApiOperation("首页公告列表")
    @ApiOperationSupport(order = 10)
    public JsonResult listNotice(){
        //先到redis中查有没有
        //get key
//        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();//操作字符串的
//        Serializable noticeIndex = ops.get("notice_index");
        Serializable noticeIndex = cacheUtil.get("notice_index");
        if (noticeIndex != null){//缓存中如果有
            log.debug("首页数据来自redis数据库");
            return JsonResult.ok(noticeIndex);
        }
        //如果缓存中没有
        log.debug("首页数据来自mysql数据库");
        List<NoticeListVO> noticeListVOS =noticeMapper.selectNoticeList();
        log.debug("noticeListVOS = " + noticeListVOS);
       //在redis中存一份,并设置缓存的时间，不设置缓存时间是不合理的
//        ops.set("notice_index", (Serializable) noticeListVOS,30, TimeUnit.SECONDS);
        cacheUtil.setExpire("notice_index",(Serializable) noticeListVOS,30);
        return JsonResult.ok(noticeListVOS);
    }
}
